﻿@using KC.MVC.Core.Constants
@using KC.Web.Account.Constants
@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService AuthorizationService
@{
    ViewBag.Title = "组织架构管理";
    Layout = "~/Views/Shared/_ListLayout.cshtml";
}

<div id="toolbar">
    <div>
        @*组织架构管理-保存组织架构*@
        @if ((await AuthorizationService.AuthorizeAsync(User, "0EBCF1F7-3E2A-4A0E-AF90-36689ABB0AA3")).Succeeded)
        {
            <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="fa fa-plus" onclick="addOrganization()">新增</a>
        }
        @*组织架构管理-保存组织架构*@
        @if ((await AuthorizationService.AuthorizeAsync(User, "0EBCF1F7-3E2A-4A0E-AF90-36689ABB0AA3")).Succeeded)
        {
            <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="fa fa-pencil" onclick="editOrganization()">编辑</a>
        }
        @*组织架构管理-删除组织架构*@
        @if ((await AuthorizationService.AuthorizeAsync(User, "93F6DC06-6426-41DF-9DB8-C0FA0758FBB7")).Succeeded)
        {
            <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="fa fa-trash" onclick="removeOrganization()">删除</a>
        }
    </div>

    <div>
        部门名称：
        <input id="txtSearchbox" class="easyui-textbox" placeholder="请输入部门名称" style="width: 300px; height: 26px;" />
        <a href="javascript:void(0)" onclick="reloadDatagrid()" class="easyui-linkbutton" data-options="iconCls:'fa fa-search'">查询</a>
        <a href="javascript:void(0)" onclick="RefreshSearch()" class="easyui-linkbutton ListToolEndBtn" data-options="iconCls:'fa fa-refresh'">刷新</a>
    </div>
</div>

<table id="datagrid"></table>
@section scripts
    {
    <script type="text/javascript">
        $.extend($.fn.validatebox.defaults.rules, {
            repeatTreeCode: {
                validator: function (value) {
                    var reg = /^[0-9a-zA-Z]+$/;

                    return reg.test(value);
                },
                message: '请输入有效的部门代码'
            }
        });

        $(function() {
            InitTreeDataGrid();
        });

        
        var loadDataUrl = '@Url.Action(ActionName.Organization.LoadOrganizationList, ControllerName.Organization)';
        var IsCheckFlag = false; //是否选中的标志
        var rowIndexTo; //保存当前保存的是那条数据
        function InitTreeDataGrid() {
            $('#datagrid').treegrid({
                url: loadDataUrl,
                method: 'get',
                idField: 'id',
                treeField: 'text',
                fitColumns: true,
                rownumbers: true,
                singleSelect: true,
                checkOnSelect: true,
                nowrap: false,
                fit: true,
                lines: true,
                showFooter: false,
                toolbar: "#toolbar",
                //toolbar: [{ text: document.getElementById('toolbar') }],
                columns: [
                    [
                        { field: 'id', title: '编号', width: 120, align: 'left', hidden: true },
                        { field: 'text', title: '名称', width: 140, align: 'left' },
                        { field: 'UserNamesInfo', title: '下属员工', width: 240, align: 'left' },
                        { field: 'BusinessTypeString', title: '归属业务', width: 120, align: 'left' },
                        { field: 'Level', title: '层级', width: 100, align: 'left' },
                        { field: 'Index', title: '排序', width: 100, align: 'left' }
                    ]
                ],
                onBeforeLoad: function(param) {

                },
                onLoadSuccess: function(data) {
                    $(".btnContacts").linkbutton({ plain: true, iconCls: 'fa fa-search' });
                },
                onLoadError: function() {
                },
                onSelect: function(rowIndex, rowData) {
                    if (!IsCheckFlag) {
                        IsCheckFlag = true;
                        rowIndexTo = rowIndex;
                    } else if (rowIndexTo == rowIndex) {
                        IsCheckFlag = false;
                        $('#datagrid').treegrid("unselectAll");
                    } else {
                        IsCheckFlag = false;
                    }
                }
            });
        }

        function refreshSearch() {
            $('#datagrid').datagrid('unselectAll');
            $("#txtSearchbox").searchbox('setValue', '');
            reloadDatagrid();
        }

        function reloadDatagrid() {
            $('#datagrid').datagrid('unselectAll');
            $("#datagrid").treegrid("load", {
                name: $("#txtSearchbox").searchbox("getValue")
            });
        }

        function addOrganization() {
            var row = $('#datagrid').treegrid('getSelected');
            if (row) {
                opentForm(0, row.id);
            } else {
                opentForm(0, 0);
            }
        }

        function editOrganization() {
            var row = $('#datagrid').treegrid('getSelected');
            if (row) {
                opentForm(row.id, 0);

            } else {
                $.messager.showErrorCenter('系统提示', "请选择需要编辑的数据", 1000);
            }
        }

        var getFormUrl = '@Url.Action(ActionName.Organization.GetOrganizationForm, ControllerName.Organization)';
        var saveFormUrl = '@Url.Action(ActionName.Organization.SaveOrganizationForm, ControllerName.Organization)';
        function opentForm(id, parentId) {
            $.easyui.showDialog({
                title: id > 0 ? '编辑组织架构' : '新增组织架构',
                width: 400,
                height: 300,
                href: getFormUrl + "?id=" + id + "&&parentId=" + parentId,
                modal: true,
                topMost: false,
                enableHeaderContextMenu: false,
                enableApplyButton: false,
                onSave: function(d) {
                    var validate = d.form("enableValidation").form("validate");
                    if (validate) {
                        if ($("#level").val() == "4") {
                            $.messager.showErrorCenter("系统提示", "此父级" +' '+$("#ParentId").val()+' ' + "不能作为父级");
                            $("#level").val(' ');
                            return false;
                        }


                        $.easyui.loading({ msg: '正在保存数据，请稍等...' });
                        $.ajax({
                            async: true,
                            type: "post",
                            dataType: "json",
                            url: saveFormUrl,
                            data: AddAntiForgeryToken(d.form("getData")),
                            success: function(data) {
                                if (data.success) {
                                    d.window('close');
                                    if (data.Result) {
                                        $('#datagrid').treegrid('clearSelections');
                                        $('#datagrid').treegrid('reload');
                                        $.messager.showInfoCenter('系统提示', '保存数据成功。', 1000);
                                    } else {
                                        $.messager.showErrorCenter('错误消息', '保存数据失败。');
                                    }
                                } else {
                                    $.messager.showErrorCenter('错误消息', data.message);
                                }
                            },
                            complete: function() {
                                $.easyui.loaded();
                            }
                        });
                        return false;
                    } else {
                        return false;
                    }
                },
                onLoad: function() {
                    $('.textbox').bind('blur', function() {
                        $(this).validatebox('enableValidation').validatebox('validate');
                    });
                }
            });
        }

        var removeUrl = '@Url.Action(ActionName.Organization.RemoveOrganization, ControllerName.Organization)';
        function removeOrganization() {
            var row = $('#datagrid').treegrid('getSelected');
            if (row) {
                if (row.children.length > 0) {
                    $.messager.showErrorCenter('错误消息', '无法删除有子部门的部门，请先删除子部门后再重试。', 1000);
                    return;
                }

                $.messager.confirm('系统提示', '确认要删除选中行?', function(r) {
                    if (r) {
                        $.easyui.loading({ msg: '正在保存数据，请稍等...' });
                        $.post(removeUrl, { id: row.id }, function(data) {
                            if (data.success) {
                                if (data.Result) {
                                    $('#datagrid').treegrid('clearSelections');
                                    $('#datagrid').treegrid('reload');
                                    $.messager.showInfoCenter('系统提示', '删除数据成功。', 1000);
                                } else {
                                    $.messager.showErrorCenter('错误消息', '删除数据失败。');
                                }
                            } else {
                                $.messager.showErrorCenter('错误消息', data.message);
                            }
                            $.easyui.loaded();
                        });
                    }
                });
            } else {
                $.messager.showErrorCenter('系统提示', "请选择需要删除的数据", 1000);
            }
        }
    </script>
}

